public class list3 {
/* 
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val, ListNode next) { this.val = val; this.next = next;}
        ListNode(int val) {this.val = val;}
    }
*/

    public static void main(String[] args) {
        System.out.println("Hello List");
        //list1 ll = new list1();
        //list1.ListNode node1 = ll.new ListNode(1);
        ListNode head = new ListNode();
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode last = null;
        //head.next = node1;
        head = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = last;
        
        /* 
        System.out.println("The value of node1=" + node1.val);
        System.out.println("The value of node2=" + node2.val);
        System.out.println("The value of node3=" + node3.val);
        System.out.println("The value of node4=" + node4.val);
        System.out.println("The value of node5=" + node5.val);
        */
        ListNode r = new ListNode();
        r = reverseList(head);
        //r = r.next;
        System.out.println("The value of the r is " + r.val);
        
        while (r != null) {
            System.out.println("The node value is " + r.val );
            r = r.next;
        }
        

    }

    public static ListNode reverseList(ListNode head) {
    
    
        ListNode last = null; // 前一個節點

        while (head != null) {
            ListNode nextNode = head.next; // 先把下一個node存起來
            head.next = last; //反轉，下一個
            last = head; // 記住當個節點，作為下一個節點的上一個
            head = nextNode; // 設完了，將head指向下一個節點
            // head.next 已先被改成last, 不是原先的下一個
        }
        //System.out.println("reverseList: The value of head is " + head.val);
        return last;
    }
    
}
